﻿/// <reference path="../devextreme/ts/jquery.d.ts" />

($ => {
    $.fn.reportVideoListWrapper = function (options) {
        options = options || {};

        handleGetVideos = () => {
            return new Promise(resolve => {
                $.ajax({
                    url: `${options.url}/${options.reportId}/get-study-base-info`,
                    type: 'GET',
                    dataType: 'json',
                    contentType: 'application/json;charset=UTF-8',
                    success: result => {
                        if (options.getVideos instanceof Function && result.data) {
                            options.getVideos(result.data).then(data => {
                                resolve(data);
                            });
                        }
                    },
                    error: () => {
                        resolve([]);
                    }
                })
            });
        };

        handleViewVideo = video => {
            return new Promise(resolve => {
                if (options.viewVideo instanceof Function) {
                    options.viewVideo(video).then(() => {
                        resolve();
                    });
                }
            });
        };

        handleImportVideos = () => {
            return new Promise(resolve => {
                $.ajax({
                    url: `${options.url}/${options.reportId}/get-study-base-info`,
                    type: 'GET',
                    dataType: 'json',
                    contentType: 'application/json;charset=UTF-8',
                    success: result => {
                        if (options.importVideos instanceof Function && result.data) {
                            options.importVideos(result.data).then(data => {
                                resolve(data);
                            });
                        }
                    },
                    error: () => {
                        resolve([]);
                    }
                })
            });
        };

        handleExportVideos = videos => {
            return new Promise(resolve => {
                if (options.exportVideos instanceof Function) {
                    options.exportVideos(videos).then(() => {
                        resolve();
                    });
                }
            });
        };

        handleDeleteVideos = videos => {
            return new Promise(resolve => {
                if (options.deleteVideos instanceof Function) {
                    resolve(options.deleteVideos(videos));
                }
            });
        };

        return $(this[0]).reportVideoList({
            onGetVideos: handleGetVideos,
            onViewVideo: handleViewVideo,
            onImportVideos: handleImportVideos,
            onExportVideos: handleExportVideos,
            onDeleteVideos: handleDeleteVideos,
            ...options
        });
    }
})(jQuery);